package starfire.manager;

import java.util.*;

import starfire.*;
import starfire.task.*;

/**
 * <p>Title: </p>
 * <p>Description: </p>
 * <p>Copyright: Copyright (c) 2003</p>
 * <p>Company: </p>
 * @author zzzhc.starfire@gmail.com
 * @version 1.0
 */

public class TaskManager {
  Vector tasks = null;
  Hashtable taskState = null;
  boolean startAutoDownload = false;

  private static TaskManager manager = new TaskManager();

  private TaskManager() {
    tasks = new Vector();
    taskState = new Hashtable();
  }

  public static TaskManager getTaskManager() {
    return manager;
  }

  public void addTask(Task task) {
    if (task==null)
      return;
    tasks.add(task);
    taskState.put(task, Boolean.FALSE);
  }

  public void removeTask(Task task) {
    tasks.remove(task);
    taskState.remove(task);
  }

  public void removeTask(int index) {
    taskState.remove(tasks.elementAt(index));
    tasks.remove(index);
  }

  public Iterator taskIterator() {
    return tasks.iterator();
  }

  public Task getFreeTask() {
    Iterator iterator = tasks.iterator();
    Task task = null;
    while (iterator.hasNext()) {
      task = (Task) iterator.next();
      if (! ( (Boolean) taskState.get(task)).booleanValue()) {
        return task;
      }
    }
    return null;
  }

  public Task getTask(int index) {
    return (Task) tasks.get(index);
  }

  public int getTaskSize() {
    return tasks.size();
  }

  public void startTask(int index) {
    Task task = (Task) tasks.get(index);
    startTask(task);
  }

  public void startTask(Task task) {
    if (!tasks.contains(task)) {
      tasks.add(task);
    }
    task.startAll();
  }

  public void autoDownload() {
    if (startAutoDownload == true) {
      return;
    }
    startAutoDownload = true;
    Timer timer = new Timer();
    timer.schedule(new AutoDownload(), 0, 5000);
  }

  class AutoDownload
      extends java.util.TimerTask {
    public void run() {
      Vector v = (Vector) tasks.clone();
      for (int i = 0; i < v.size(); i++) {
        try {
         final Task task = (Task) v.get(i);
          if (task.getState() == Task.TASKINIT) {
            new Thread()
            {
              public void run()
              {
                task.startAll();
              }
            }.start();
          }
          Thread.sleep(1000);
        }
        catch (Exception e) {
          e.printStackTrace();
        }
      }
    }
  }

}